#pragma once

#include <iostream>
#include <string>
#include <fstream>
#include <unordered_map>
#include "Common.hpp"
#include "Log.hpp"

const string gpath = "./";
const string gfilename = "dict.txt";
const string gsep = ": ";

using namespace LogModule;

class Dictionary
{
private:
    // 不需要暴露给外部
    bool LoadDictionary()
    {
        string file = _path + _filename;
        ifstream in(file.c_str());
        if(!in.is_open())  // 打开失败
        {
            LOG(LogLevel::ERROR) << "open file " << file << "error";
            return false;
        }
        string line;  // 获取一行
        while(getline(in, line))
        {
            // jump: 跳
            string key, value;
            if(SplitString(line, &key, &value, gsep))  // 分割成功了
            {
                // _dictionary[key] = value;
                _dictionary.insert(std::make_pair(key, value));
            }
        }
        in.close();
        return true;
    }

public:
    Dictionary(const string& path = gpath, const string& filename = gfilename)
        :_path(path)
        ,_filename(filename)
    {
        LoadDictionary();
    }

    string Translate(const string& word)
    {
        auto iter = _dictionary.find(word);
        if(iter == _dictionary.end()) return "No Such Word";
        return iter->second;
    }

    ~Dictionary(){}
private:
    unordered_map<string,string> _dictionary;  // 字典
    string _path;  // 文件路径
    string _filename;  // 文件名
};